package com.tomecode.tools.maven.settings.gui.tabs;

import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Collections;

import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;

import com.tomecode.tools.maven.settings.model.Settings;

/**
 * Tab manager
 * 
 * @author Frastia Tomas
 * 
 */
public final class TabManager extends JTabbedPane {

	private static final long serialVersionUID = -3496165260746462080L;

	private final PluginGroupsTab pluginGroupsTab;

	private final ServersTab serversTab;

	private final MirrorsTab mirrorsTab;

	private final ProxiesTab proxiesTab;

	private final ProfilesTab profilesTab;

	private final BasicTab basicTab;

	private final KeyStroke ctrlTab;

	public TabManager(Settings settings) {
		super();
		ctrlTab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK);
		basicTab = new BasicTab(settings);
		addTab("Settings", basicTab);
		pluginGroupsTab = new PluginGroupsTab(settings);
		addTab("Plugin Groups", pluginGroupsTab);
		serversTab = new ServersTab(settings);
		addTab("Servers", serversTab);
		mirrorsTab = new MirrorsTab(settings);
		addTab("Mirrors", mirrorsTab);
		proxiesTab = new ProxiesTab(settings);
		addTab("Proxies", proxiesTab);
		profilesTab = new ProfilesTab(settings);
		addTab("Profiles", profilesTab);

		// registering ctrl+tab key
		setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.singleton(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)));
		InputMap im = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		im.put(ctrlTab, "ctrlTab");
		getActionMap().put("ctrlTab", new AbstractAction("ctrlTab") {

			private static final long serialVersionUID = -4338670465201740592L;

			public final void actionPerformed(ActionEvent e) {
				// ctrl+tab as an action to move to next tab
				if (getSelectedIndex() + 1 >= getComponentCount()) {
					setSelectedIndex(0);
				} else {
					setSelectedIndex(getSelectedIndex() + 1);
				}
			}
		});

		setSelectedIndex(0);
	}
}
